<template>
  <view class="container">
    <view class="navbar">
      <text class="back-btn" @click="navigateBack">
        <uni-icons type="left" size="20" color="#ffffff"></uni-icons>
      </text>
      <text class="title">评价工单服务</text>
    </view>

    <view class="rating-container">
      <!-- 工单信息：展示从列表页传递的ID、标题、处理人 -->
      <view class="ticket-info">
        <text class="info-label">工单ID：</text>
        <text class="info-content">{{ ticketId || '未知' }}</text>
      </view>
      
      <view class="ticket-info">
        <text class="info-label">工单标题：</text>
        <text class="info-content">{{ ticketTitle || '未知工单' }}</text>
      </view>
      
      <view class="ticket-info">
        <text class="info-label">处理人：</text>
        <text class="info-content">{{ handlerName || '未知' }}</text>
      </view>

      <!-- 评分区域 -->
      <view class="rating-area">
        <text class="rating-label">服务评分 <span class="required">*</span></text>
        
        <view class="stars-wrapper">
          <view 
            class="star-item" 
            v-for="star in 5" 
            :key="star"
            @click="selectStar(star)"
          >
            <uni-icons 
              type="star" 
              size="36" 
              :color="star <= ratingValue ? '#faad14' : '#ddd'"
            ></uni-icons>
            <text class="star-text">{{ star }}星</text>
          </view>
        </view>
        
        <text class="rating-desc">{{ ratingDesc }}</text>
      </view>

      <!-- 评价内容 -->
      <view class="comment-area">
        <text class="comment-label">评价内容</text>
        <textarea 
          v-model="comment" 
          placeholder="请输入您的评价（可选，最多500字）"
          class="comment-input"
          maxlength="500"
        ></textarea>
        <text class="word-count">{{ comment.length }}/500</text>
      </view>

      <!-- 提交按钮 -->
      <button 
        class="submit-btn"
        @click="submitRating"
        :disabled="ratingValue === 0 || isSubmitting"
      >
        <text v-if="!isSubmitting">提交评价</text>
        <text v-if="isSubmitting">提交中...</text>
      </button>
    </view>
  </view>
</template>

<script>
import request from '@/api/request.js';
import uniIcons from '@dcloudio/uni-ui/lib/uni-icons/uni-icons.vue';

export default {
  components: {
    uniIcons
  },
  data() {
    return {
      ticketId: null,       // 接收的工单ID
      ticketTitle: '',      // 接收的工单标题
      handlerName: '',      // 接收的处理人
      ratingValue: 0,       // 选中的评分（1-5）
      comment: '',          // 评价内容
      ratingDesc: '请选择1-5星评分', // 评分描述
      isSubmitting: false,  // 提交中状态
      token: uni.getStorageSync('token') || '' // 登录态token
    };
  },

  onLoad(options) {
    // 从路由参数接收工单ID、标题、处理人
    this.ticketId = options.orderId || '未知';
    this.ticketTitle = decodeURIComponent(options.title) || '未知工单';
    this.handlerName = decodeURIComponent(options.employeeName) || '未知';

    // 检查登录态
    if (!this.token) {
      uni.showToast({ title: '请先登录', icon: 'none' });
      setTimeout(() => {
        uni.redirectTo({ url: '/pages/login/login' });
      }, 1500);
      return;
    }
  },

  methods: {
    // 返回上一页
    navigateBack() {
      uni.navigateBack({ delta: 1 });
    },

    // 选择评分（更新评分值和描述）
    selectStar(star) {
      this.ratingValue = star;
      this.updateRatingDesc();
      this.$forceUpdate(); // 强制更新视图
    },

    // 更新评分描述
    updateRatingDesc() {
      switch (this.ratingValue) {
        case 1:
          this.ratingDesc = '1星 - 非常不满意';
          break;
        case 2:
          this.ratingDesc = '2星 - 不满意';
          break;
        case 3:
          this.ratingDesc = '3星 - 一般';
          break;
        case 4:
          this.ratingDesc = '4星 - 满意';
          break;
        case 5:
          this.ratingDesc = '5星 - 非常满意';
          break;
        default:
          this.ratingDesc = '请选择1-5星评分';
      }
    },

    // 提交评价
    async submitRating() {
      // 评分校验：必须选1-5星
      if (this.ratingValue < 1 || this.ratingValue > 5) {
        uni.showToast({ title: '请选择1-5星评分', icon: 'none' });
        return;
      }

      // 从传递的参数中取工单ID（必须存在）
      const orderId = this.ticketId;
      if (!orderId) {
        uni.showToast({ title: '工单ID异常，无法评价', icon: 'none' });
        return;
      }

      this.isSubmitting = true;
      try {
        // 构造后端要求的请求体
        const requestBody = {
          orderId: orderId,      // 工单ID（从列表页传递）
          rating: this.ratingValue, // 评分值
          comment: this.comment.trim() // 评价内容（去空格）
        };

        // 调用评价接口
        const response = await request.postJson(
          '/api/customerFeedback/addFeedback',
          requestBody, // 传递请求体
          true,
          { Token: this.token } // 携带登录态
        );

        // 评价成功提示
        uni.showToast({ title: '评价提交成功', icon: 'success' });
        uni.$emit('workorderRated', { orderId }); // 通知列表页刷新
        setTimeout(() => this.navigateBack(), 1500);
      } catch (error) {
        // 错误提示细化
        let errMsg = '评价提交失败，请重试';
        switch (error.code) {
          case 100002:
            errMsg = error.msg || '参数错误，请检查工单信息';
            break;
          case 100007:
            errMsg = error.msg || '无法评价，该工单可能未结算/已评价';
            break;
          case 100003:
            errMsg = '登录已过期，请重新登录';
            uni.removeStorageSync('token');
            setTimeout(() => uni.redirectTo({ url: '/pages/login/login' }), 1500);
            break;
          case 100001:
            errMsg = '系统异常，请稍后重试';
            break;
        }
        uni.showToast({ title: errMsg, icon: 'none' });
      } finally {
        this.isSubmitting = false;
      }
    }
  }
};
</script>

<style scoped>
/* 页面样式保持不变 */
.container {
  background-color: #f5f7fa;
  min-height: 100vh;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}

.navbar {
  height: 44px;
  background-color: #5555ff;
  display: flex;
  align-items: center;
  padding: 0 15px;
  position: relative;
}

.back-btn {
  color: #ffffff;
  font-size: 20px;
  z-index: 10;
  display: flex;
  align-items: center;
}

.title {
  color: #ffffff;
  font-size: 18px;
  font-weight: 500;
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}

.rating-container {
  padding: 20px 15px;
}

.ticket-info {
  margin-bottom: 12px;
  padding-bottom: 12px;
  border-bottom: 1px solid #eeeeee;
  font-size: 14px;
}

.info-label {
  color: #86909c;
  margin-right: 8px;
}

.info-content {
  color: #272e3b;
}

.rating-area {
  margin: 25px 0;
}

.rating-label {
  display: block;
  color: #272e3b;
  font-size: 16px;
  margin-bottom: 15px;
  font-weight: 500;
}

.required {
  color: #ff4d4f;
  font-size: 14px;
}

.stars-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  padding: 10px 0;
}

.star-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 20%;
  padding: 10px 5px;
  cursor: pointer;
  touch-action: manipulation;
  -webkit-tap-highlight-color: rgba(0, 0, 0, 0.1);
}

.star-text {
  font-size: 12px;
  color: #86909c;
  margin-top: 5px;
}

.rating-desc {
  color: #86909c;
  font-size: 14px;
  margin-top: 5px;
  min-height: 20px;
}

.comment-area {
  margin-bottom: 30px;
}

.comment-label {
  display: block;
  color: #272e3b;
  font-size: 16px;
  margin-bottom: 10px;
  font-weight: 500;
}

.comment-input {
  width: 100%;
  height: 150px;
  background-color: #ffffff;
  border: 1px solid #e5e6eb;
  border-radius: 8px;
  padding: 12px;
  font-size: 14px;
  color: #272e3b;
  line-height: 1.5;
  resize: none;
}

.word-count {
  display: block;
  text-align: right;
  color: #86909c;
  font-size: 12px;
  margin-top: 5px;
}

.submit-btn {
  width: 100%;
  background-color: #165dff;
  color: #ffffff;
  padding: 12px 0;
  border-radius: 8px;
  font-size: 16px;
  margin-top: 20px;
}

.submit-btn:disabled {
  background-color: #86909c;
  opacity: 0.8;
}
</style>